#!/bin/bash -eu

#
# Upload signed .safariextz to S3
#

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
ROOT_DIR="$( cd "$DIR"/../.. && pwd )"

. "$ROOT_DIR/init.sh"

S3_PATH="$S3_BUCKET/connector/safari/"
EXTZ="`"$DIR"/get_extz_path`"
VERSION="$( xar -x -f "$EXTZ" --to-stdout | grep -C 2 CFBundleVersion | head -n 2 | tail -n 1 | sed -n -E 's/.*<string>([0-9.]+(beta[0-9]+)?)<\/string>.*/\1/p' )"

if [ -z "$VERSION" ]; then
	echo "Error extracting version from Info.plist"
	exit 1
fi

# Check signature
CERT_FILE="$BUILD_DIR/safari_certs.pem"
xar -f "$EXTZ" --extract-CAfile "$CERT_FILE"

if ! openssl x509 -subject -in "$CERT_FILE" -noout | grep --quiet $SAFARI_DEVELOPER_ID; then
	echo "$EXTZ is not signed"
	exit 1
fi
rm "$CERT_FILE"

aws s3 cp --content-type application/octet-stream "$EXTZ" s3://${S3_PATH}Zotero_Connector-$VERSION.safariextz
rm "$EXTZ"
